sub = {
    "op": "subscribe",
    "id": "subscribe:/ubiquityrobot/camera_node/image_raw/compressed:6",
    "type": "sensor_msgs/CompressedImage",
    "topic": "/ubiquityrobot/camera_node/image_raw/compressed",
    "compression": "none",
    "throttle_rate": 0,
    "queue_length": 0
}

unsub = {
    "op": "unsubscribe",
    "id": "subscribe:/ubiquityrobot/camera_node/image_raw/compressed:6",
    "topic": "/ubiquityrobot/camera_node/image_raw/compressed"
}

import asyncio
from camera_utils.easy_websocket import EasyClient
from websockets import WebSocketCommonProtocol
import json
import threading

client = EasyClient()
callback = None

class WebsocketCamera:

    def __init__(self, host, cb=None):
        global callback
        self.url = 'ws://' + host + ':9090'
        callback = cb
        print(callback,cb)
        self.active = True
        self.thread_loop = asyncio.new_event_loop() 
        self._reader = threading.Thread(target=self.start, args=(self.thread_loop,))
        self._reader.deamon = True
        self._reader.start()
        # self.start(self.thread_loop)

    @client.init_event()
    async def auth(websocket: WebSocketCommonProtocol):
        await websocket.send(json.dumps(sub))
        print("send", json.dumps(sub))
        return
        msg = await websocket.recv()
        if msg != "ok":
            await websocket.close(code=1008)

    @client.event()
    async def on_message(websocket: WebSocketCommonProtocol):
        while True:
            data = await websocket.recv()
            # print(f"Client get message: ")
            if callback is not None:
                try:
                    obj = json.loads(data)
                    callback(obj['msg'])
                except Exception as e:
                    print(e)
            # print(f"Client get message: {msg}")
            # await websocket.close()

    @client.event()
    async def heartbeat(websocket: WebSocketCommonProtocol):
        while True:
            await websocket.send("Heartbeat")
            await asyncio.sleep(5)

    def start(self,loop):
        try:
            client.start(self.url,loop)
        except Exception as e:
            print(e,1)
            self.active = False

    def release(self):
        try:
            client.websocket.close()
        except Exception as e:
            print(e,2)
        client.stop()

    def isOpened(self):
        return self.active

if __name__ == '__main__':
  import time
  camera = WebsocketCamera('localhost')
  time.sleep(3)
  camera.thread_loop.stop()
  time.sleep(1)
  camera.thread_loop.stop()
  time.sleep(1)
  camera = WebsocketCamera('192.168.50.24')
  time.sleep(3)
  camera.thread_loop.stop()
  print('over')